#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mysqlite=new MySQLite;
    mysqlite->create_database_table();
    model=new QSqlQueryModel(this);
    //connect(ui->pushButton_start,&QPushButton::clicked,ui->connect_setup,&Connect_Setup::open_serialport);
    connect(ui->pushButton_start,&QPushButton::clicked,[=](){ui->connect_setup->open_serialport();});
    //connect(ui->pushButton_start,&QPushButton::clicked,this,&MainWindow::set_pushbutton_start);
    connect(ui->connect_setup,SIGNAL(send_currentindex(int)),this,SLOT(set_pushbutton_start(int)));
    connect(ui->pushButton_send,&QPushButton::clicked,this,&MainWindow::send_message);
    connect(ui->connect_setup->serial,&QSerialPort::readyRead,this,&MainWindow::receive_message);
    connect(ui->connect_setup->myserver,SIGNAL(send_message(QString)),this,SLOT(receive_socket_message(QString)));
    connect(ui->pushButton_sendTemperature,&QPushButton::clicked,this,&MainWindow::send_random_temperature);


}

MainWindow::~MainWindow()
{
    delete ui;
    delete mysqlite;
    delete model;
}

void MainWindow::set_model()
{
    model->setQuery("select * from water_temperature");
    model->setHeaderData(0,Qt::Horizontal,tr("日期时间"));
    model->setHeaderData(1,Qt::Horizontal,tr("温度"));
    ui->tableView->setModel(model);
    ui->tableView->verticalHeader()->setHidden(true);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

void MainWindow::receive_message()
{
    QString message;
    message.append(ui->connect_setup->serial->readAll());
    if(message.indexOf("this is water temperature:")!=-1)//判断传过来的数据是否是水温
    {
        QStringList strlist=message.split(":");
        QString message_head=strlist.at(0);//解析消息头
        QString message_temperature=strlist.at(1);//解析消息本体
        int temperature=message_temperature.toInt();
        //如果是水温,将该数据存入数据库表
        QString datetime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");//获取系统当前时间，并格式化时间
        datetime="'"+datetime+"'";
        QString database_command;
        database_command="insert into water_temperature (date_time,temperature) values ("+ datetime+","+message_temperature+");";
        //qDebug()<<database_command;
        mysqlite->database_operation(database_command);
        mysqlite->select_data();
        set_model();

       ui->graphicsView->update_data(QDateTime::currentDateTime(),temperature);
    }
    else
    {
        qDebug()<<message;
        ui->textEdit_ReceiveMessage->insertPlainText(message+='\n');
    }

}

void MainWindow::send_random_temperature()
{
    if(ui->pushButton_sendTemperature->text()=="发送水温")
    {
        ui->pushButton_sendTemperature->setText("停止发送");
        while(ui->pushButton_sendTemperature->text()=="停止发送")
        {
            int temperature=Random_temperature::Generate_random_water_temperature();
            QString str="this is water temperature:"+QString::number(temperature);
            QByteArray temperaturesend;
            temperaturesend.append(str);
            ui->connect_setup->serial->write(temperaturesend);
            //QThread::sleep(3);
            QTime time=QTime::currentTime().addSecs(3);
            while(QTime::currentTime()<time)
                QCoreApplication::processEvents();
        }
    }
    else
        ui->pushButton_sendTemperature->setText("发送水温");


}

void MainWindow::receive_socket_message(QString msg)
{
    ui->textEdit_ReceiveMessage->insertPlainText(msg);
}


void MainWindow::set_pushbutton_start(int currentIndex)
{
    if(currentIndex==0)
    {
        if(ui->connect_setup->serial->isOpen())
            {
                ui->pushButton_start->setText("停止");
            }
        else
            {
                ui->pushButton_start->setText("启动");
            }
    }
    else if(currentIndex==1)
    {
        if(ui->connect_setup->myserver->isListening())
        {

            ui->pushButton_start->setText("停止监听");
        }
        else
            ui->pushButton_start->setText("启动");
    }
}

void MainWindow::send_message()
{
    QString message=ui->textEdit_SendMessage->toPlainText();
    QByteArray messageSend;
    messageSend.append(message);
    if(ui->connect_setup->serial->isOpen())
        ui->connect_setup->serial->write(messageSend);
    else if (ui->connect_setup->myserver->isListening())
    {
        ui->connect_setup->myserver->sendtoClient(ui->connect_setup->get_comboBox_Clientip(),messageSend);
    }
}

